package com.leef.glidetest.utils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by IWALL on 2016/1/5.
 * BitmapFactory decodeStream 专用的解密输入流（扩展对称解密）
 */
public class DecBufferedInputStream extends BufferedInputStream {
    public static final int VOR = 0xAA;
    private int vor;

    public DecBufferedInputStream(InputStream in, int vor) {
        super(in);
        this.vor = vor;
    }

    @Override
    public synchronized int read(byte[] b, int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }

        int c = read();
        if (c == -1) {
            return -1;
        }
        b[off] = (byte) c;

        int i = 1;
        try {
            for (; i < len; i++) {
                c = read();
                if (c == -1) {
                    break;
                }
                b[off + i] = (byte) c;
            }

            //  拷贝一份当前数据
            byte[] tmp = new byte[i];
            System.arraycopy(b, 0, tmp, 0, i);
            //  将数据加密后回写
            for (int j = 0; j < i; j++) {
                tmp[j] = (byte) (tmp[j] ^ vor);
            }
            System.arraycopy(tmp, 0, b, 0, i);

        } catch (IOException ee) {
            ee.printStackTrace();
        }
        return i;
    }
}